const Router = require('koa-router')
const router = new Router();
const jwt = require('jsonwebtoken')
const key = 'wfidqnmwoeqwpdqw'

const userList = [{
  username: 'admin',
  tel: '13111111111',
  email: '123456@qq.com',
  password: 'admin',
  nickname: '小小管理员',
  avator: 'https://robohash.org/123?set=set5',
  role: 'admin'
}, {
  username: 'zhangsan',
  tel: '13222222222',
  email: '123456@163.com',
  password: 'zhangsan',
  nickname: '小小三三',
  avator: 'https://robohash.org/123?set=set4',
  role: 'user'
}, {
  username: 'lisi123',
  tel: '13333333333',
  email: '123456@bawei.com',
  password: 'lisi123',
  nickname: '小小四先生',
  avator: 'https://robohash.org/123?set=set3',
  role: 'test'
}]

router.post('/login', ctx => {
  // 1.  获取发送过来用户名和密码
  const { username, password } = ctx.request.body
  // 2. 登录校验
  const user = userList.find(v => {
    return (v.username === username && v.password === password)
      || (v.email === username && v.password === password)
      || (v.tel === username && v.password === password)
  })
  if(user) {
    const userInfo = {
      username: user.username,
      role: user.role,
      nickname: user.nickname,
      email: user.email,
      tel: user.tel,
      avator: user.avator,
    }
    ctx.body = {
      code: 200,
      data: {
        userInfo: userInfo,
        token: jwt.sign(userInfo, key)
      },
      message: '登录成功， 欢迎' + user.nickname
    }
  } else {
    ctx.body = {
      code: 401,
      message: '账户密码错误， 请重新登录'
    }
  }
  
})


module.exports = router